(function(w) {
	var service = {
		//		apiServer: 'http://next.ff-pm.com/', //接口前缀
		apiServer: 'http://beta.ff-pm.com/', //测试服务器接口前缀
		//		apiServer: 'http://192.168.69.122:8080/',
		/**
		 * jsonp请求函数
		 * @param {String} url
		 * @param {Object} param
		 * @param {String} showWaiting
		 * @param {String} waitingText
		 */
		jsonp: function(url, param, showWaiting, waitingText) {
			if(window.plus) {
				if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE)
					return Promise.reject({
						message: '当前未连接网络，请连接后再试'
					});
			}
			return new Promise(function(resolve, reject) {
				if(window.plus && showWaiting)
					Util.showNativeWaiting(waitingText);

				Vue.http.jsonp(url, {
					params: param,
				}).then(function(res) {
					res.json().then(function(data) {
						resolve(data);
					})
				}).catch(function() {
					reject({
						message: '服务器开小差，稍后再试'
					});
				}).finally(function() {
					if(window.plus && showWaiting)
						plus.nativeUI.closeWaiting();
				})
			});
		},
		ajax: function(method, url, param, showWaiting, waitingText) {
			if(window.plus) {
				if(plus.networkinfo.getCurrentType() == plus.networkinfo.CONNECTION_NONE)
					return Promise.reject({
						message: '当前未连接网络，请连接后再试'
					});
			}
			//			console.log(url);
			//			console.log(JSON.stringify(param));
			return new Promise(function(resolve, reject) {
				if(window.plus && showWaiting)
					Util.showNativeWaiting(waitingText);

				mui.ajax(url, {
					data: param,
					dataType: 'json', //服务器返回json格式数据
					type: method, //HTTP请求类型
					//					headers: {//服务器只支持key-value获取，value如果是对象，需转为字符串
					//						'Content-Type': 'application/json'
					//					},
					timeout: 15000, //超时时间设置为15秒；
					success: function(data) {
						if(window.plus && showWaiting)
							plus.nativeUI.closeWaiting();
						resolve(data);
						//						console.log(JSON.stringify(data));
					},
					error: function(xhr, type, errorThrown) {
						console.log('请求错误：' + type + ' ' + (errorThrown && errorThrown.message));
						if(window.plus && showWaiting)
							plus.nativeUI.closeWaiting();
						reject({
							message: '服务器开小差，稍后再试'
						});
					}
				});
			});

		},
		get: function(url, param, showWaiting, waitingText) {
			return this.ajax('get', url, param, showWaiting, waitingText);
		},
		post: function(url, param, showWaiting, waitingText) {
			return this.ajax('post', url, param, showWaiting, waitingText);
		},
		/**
		 * 登录接口 //20170630 OK
		 * @param {Object} param 用户名和密码
		 */
		login: function(param) {
			var url = this.apiServer + "hfwy/a/jt/checkroomnew/login";
			return this.post(url, param, true).then(function(data) {
				if(data.flag == 1) {
					return Promise.resolve(data.data);
				} else
					return Promise.reject({
						message: '用户名或密码不正确'
					})
			});
		},
		/**
		 * 修改密码 //20170701 OK
		 * @param {String} oldPwd
		 * @param {String} newPwd
		 */
		modifyPassword: function(oldPwd, newPwd) {
			var url = this.apiServer + "hfwy/a/jt/checkroomnew/editPassword";
			return this.post(url, {
				userId: this.getCurUser().id,
				oldPassword: oldPwd,
				newPassword: newPwd
			}, true).then(function(data) {
				if(data.flag == 1) {
					return Promise.resolve(true);
				} else
					return Promise.reject(data);
			});
		},
		/**
		 * 获取基础数据列表
		 * 
		 */
		getBasicDataList: function() {
			var url = this.apiServer + "hfwy/a/jt/checkroomnew/getBusinessDataList";
			var _this = this;
			return new Promise(function(resolve, reject) {
				Util.showNativeWaiting('下载基础数据...');
				_this.post(url, {
					updateDate: ''
				}).then(function(data) {
					_this.processBasicData(data).then(resolve).catch(reject);
				}).catch(function(e) {
					plus.nativeUI.closeWaiting();
					reject(e);
				});
			})
		},
		/**
		 * 获取基础数据的更新
		 * 2017.07.06
		 */
		getBasicDataListUpdate: function(time, showWating) {
			var url = this.apiServer + "hfwy/a/jt/checkroomnew/getBusinessDataList";
			var _this = this;

			return new Promise(function(resolve, reject) {
				showWating && Util.showNativeWaiting('检测基础数据更新...');
				_this.post(url, {
					updateDate: time
				}).then(function(data) {
					_this.processBasicData(data, true).then(resolve).catch(reject);
				}).catch(function(e) {
					plus.nativeUI.closeWaiting();
					resolve(e);
				});
			})
		},
		/**
		 * 处理基础数据
		 * @param {Object} data
		 */
		processBasicData: function(data, isUpdate) {
			var _this = this;
			return new Promise(function(resolve, reject) {
				if(data.flag == 1) {
					data = data.data[0];
					var count = 0;
					_.each(data, function(item) {
						count += 1;
					})

					var cb = function() {
						count--;
						if(count == 0) {
							plus.nativeUI.closeWaiting();
							resolve(true);
						}
					}
					//检测部位
					var tmpParts = [],
						removeParts = [];
					_.each(data.examinationSiteInfo, function(item, index) {
						if(item.del_flag != '1')
							tmpParts.push({
								id: item.id,
								name: item.siteName
							});
						if(item.del_flag == '1' && isUpdate) {
							removeParts.push(item.id)
						}
					});
					dao.addPart(tmpParts).then(cb);
					if(isUpdate)
						dao.deleteParts(removeParts);

					//检测项
					var tmpCheckItems = [],
						removeCheckItems = [];
					_.each(data.checkItem, function(item, index) {
						if(item.del_flag != '1')
							tmpCheckItems.push({
								id: item.id,
								name: item.name,
								description: item.description,
								type: item.type || '2'
							});
						if(item.del_flag == '1' && isUpdate) {
							removeCheckItems.push(item.id);
						}
					})
					dao.addCheckItem(tmpCheckItems).then(cb);
					if(isUpdate)
						dao.deleteCheckItem(removeCheckItems);

					//检测项描述
					var tmpDescs = [],
						removeDescs = [];
					_.each(data.checkItemDesciption, function(item, index) {
						if(item.del_flag != '1')
							tmpDescs.push({
								id: item.id,
								name: item.content,
								item_id: item.item_id
							});
						if(item.del_flag == '1' && isUpdate) {
							removeDescs.push(item.id);
						}
					})
					dao.addCheckItemDesc(tmpDescs).then(cb);
					if(isUpdate)
						dao.deleteItemDesc(removeDescs);

					//承建商
					var tmpContractors = [],
						removeContractors = [];
					_.each(data.partContractor, function(item, index) {
						if(item.del_flag != '1')
							tmpContractors.push({
								id: item.id,
								name: item.full_name
							});
						if(item.del_flag == '1' && isUpdate) {
							removeContractors.push(item.id);
						}
					})
					dao.addContractor(tmpContractors).then(cb);
					if(isUpdate)
						dao.deleteContractor(removeContractors);

					//检查部位-检查项关系
					var tmpPartItems = [],
						removePartItems = [];
					_.each(data.partItem, function(item, index) {
						if(item.del_flag != '1')
							tmpPartItems.push({
								id: item.id,
								partId: item.part_id,
								itemId: item.item_id
							});
						if(item.del_flag == '1' && isUpdate) {
							removePartItems.push(item.id);
						}
					})
					dao.addPartCheckItemRelation(tmpPartItems).then(cb);
					if(isUpdate)
						dao.deletePartCheckItemRelation(removePartItems);

				} else {
					plus.nativeUI.closeWaiting();
					reject(data);
				}
			});
		},
		/**
		 * 检查基础数据是否已经下载
		 * 
		 */
		checkBasicData: function(shouldUpdate, showUpdateWaiting) {
			if(Service.getCurUser().id == 1) //1为本地测试用户
				return Promise.resolve();

			var lcKey = 'hf_yf_basic_data_downloaded';
			var bsTimeKey = 'hf_yf_basic_data_download_time';
			var _this = this;
			if(localStorage.getItem(lcKey)) {
				if(!shouldUpdate)
					return Promise.resolve();

				console.log('更新基础数据');
				return this.getBasicDataListUpdate(localStorage.getItem(bsTimeKey), showUpdateWaiting).then(function() {
					localStorage.setItem(bsTimeKey, (new Date()).format('yyyy-MM-dd hh:mm:ss'));
					return Promise.resolve(true);
				}).catch(function() {
					return Promise.reject(true);
				})

			} else {
				return this.getBasicDataList().then(function(data) {
					localStorage.setItem(bsTimeKey, (new Date()).format('yyyy-MM-dd hh:mm:ss'));
					localStorage.setItem(lcKey, true);
					return Promise.resolve();
				}).catch(function(e) {
					mui.toast(e.message);
					return Promise.reject();
				})
			}
		},
		clear: function() {
			localStorage.removeItem('hf_yf_basic_data_downloaded');
		},
		/**
		 * 下载单元的所有数据
		 * 
		 */
		downloadUnit: function(unitInfo, notify) {
			var url = this.apiServer + "hfwy/a/jt/checkroomnew/downLoadRoomInfo";
			var _this = this;
			unitInfo.userId = this.getCurUser().id;
			unitInfo.status = 'create';
			unitInfo.updateDate = '';
			return new Promise(function(resolve, reject) {
				_this.post(url, unitInfo).then(function(data) {
					_this.processUnitData(unitInfo, data, notify).then(function() {
						var houseList = data.data[0].room,
							houseCount = data.data[0].room.length;
						_.each(houseList, function(house) {
							if(house.del_flag != '1')
								_this.updateHouseStatus(house.id + '').then(function() {
									houseCount--;
									if(houseCount == 0) {
										resolve();
									}
								})
							else {
								houseCount--;
								if(houseCount == 0) {
									resolve();
								}
							}
						})
					}).catch(reject);
				}).catch(reject);
			})
		},
		/**
		 * 检查已下载的单元是否有更新的数据
		 * @param {Array} units
		 */
		checkUpdateByUnits: function(units, showWating) {
			showWating && Util.showNativeWaiting('检查更新...');

			var url = this.apiServer + "hfwy/a/jt/checkroomnew/downLoadRoomInfo";
			var _this = this;

			var count = units.length;
			if(count == 0) {
				plus.nativeUI.closeWaiting();
				return Promise.resolve();
			}

			return new Promise(function(resolve, reject) {
				_.each(units, function(unitInfo) {
					unitInfo.userId = _this.getCurUser().id;
					unitInfo.status = 'update';
					_this.post(url, unitInfo).then(function(data) {
						_this.processUnitData(unitInfo, data, null, true).then(function() {
							//更新后需要更新所有房间的状态
							var houseCount = 0;
							var houseList = {};
							_.each(data.data[0].problems, function(p) {
								if(!houseList[p.house_id]) {
									houseList[p.house_id] = 1;
									houseCount++;
								}
							})

							if(!houseCount) {
								count--;
								if(count == 0) {
									plus.nativeUI.closeWaiting();
									resolve();
								}
								return;
							}

							_.each(houseList, function(val, house) {
								_this.updateHouseStatus(house).then(function() {
									houseCount--;
									if(houseCount == 0) {
										count--;
										if(count == 0) {
											plus.nativeUI.closeWaiting();
											resolve();
										}
									}
								})
							})
						}).catch(reject);
					}).catch(function() {
						plus.nativeUI.closeWaiting();
						reject();
					});
				})

			})
		},
		/**
		 * 更新房间的状态
		 * @param {String} houseId
		 */
		updateHouseStatus: function(houseId) {
			return new Promise(function(resolve, reject) {
				dao.getProblemsStateCountByHouse(houseId).then(function(counts) {
					var state = Util.houseState.not_check;
					if(counts[Util.problemState.not_send] || counts[Util.problemState.not_fix])
						state = Util.houseState.not_fix;
					else if(counts[Util.problemState.fixed])
						state = Util.houseState.fixed;
					else if(counts[Util.problemState.passed])
						state = Util.houseState.passed;

					dao.updateHouse({
						id: houseId,
						state: state
					}).then(resolve);
				})
			})
		},
		/**
		 * 处理下载下来的数据
		 * @param {Object} unitInfo
		 * @param {Object} data
		 * @param {Object} resolve
		 * @param {Object} reject
		 * @param {Object} notify
		 */
		processUnitData: function(unitInfo, data, notify, isUpdate) {
			var _this = this;
			return new Promise(function(resolve, reject) {
				if(data.flag == 1) {
					data = data.data[0];
					var totalCount = 0;
					_.each(data, function(item) {
						totalCount += 1;
					})
					totalCount += 2; //复验和图片处理

					var count = 0;
					var cb = function() {
						count++;
						notify && notify(totalCount, count);
						if(totalCount == count) { //所有数据插入后再更新单元为已下载和下载时间
							dao.updateUnit({
								id: unitInfo.id,
								downloaded: 1,
								download_time: Date.now()
							}).then(resolve)
						}
					}

					//房间
					var tmpRooms = [],
						removeRooms = [];
					_.each(data.room, function(item) {
						if(item.del_flag != '1')
							tmpRooms.push({
								id: item.id + '',
								batchId: unitInfo.batchId,
								unitId: unitInfo.id,
								name: item.house_number,
								isUpdated: 0,
								floor: item.house_floor,
								state: item.rectification_status == '' ? 1 : Number(item.rectification_status),
								houseTypeId: item.house_type,
								developerName: item.developer_name,
								buildingProId: item.building_pro_info_id,
								buildingId: item.building_info_id,
								unit: item.unit
							})
						if(item.del_flag == '1' && isUpdate) {
							removeRooms.push(item.id);
						}
					});

					//承建商-房间-检查项关系
					var tmpContractorRel = [],
						removeContractorRel = [];
					_.each(data.contractor, function(item) {
						if(item.del_flag != '1')
							tmpContractorRel.push({
								id: item.id,
								contractorId: item.contractor_id,
								checkItemId: item.check_id,
								houseId: item.house_id
							})
						if(item.del_flag == '1' && isUpdate) {
							removeContractorRel.push(item.id);
						}
					});

					//问题
					var tmpProblems = [];
					var tmpRechecks = [];
					var tmpImages = [];
					var removeProblems = [];
					_.each(data.problems, function(item) {
						if(item.del_flag != '1')
							tmpProblems.push({
								id: item.id,
								batchId: item.batch_id,
								unitId: unitInfo.id,
								houseId: item.house_id,
								dataState: 0,
								state: Number(item.state),
								urgent: Number(item.status),
								partId: item.part_id,
								partName: '',
								descId: item.item_description_id,
								desc: '',
								number: item.id,
								checkItemName: '',
								checkItemId: item.item_id,
								moreDesc: item.description,
								imgBeforeFix: '',
								imgAfterFix: '',
								fixDesc: '',
								fixExpire: '',
								dutyId: item.dutyId,
								dutyName: unitInfo.developerName,
								contractorId: item.contractorId,
								contractorName: '',
								fixLive: Number(item.pass),
								createTime: item.check_date,
								fixTime: ''
							});

						if(item.del_flag == '1' && isUpdate) {
							removeProblems.push(item.id);
						}

						//复验
						_.each(item.reCheck, function(check) {
							tmpRechecks.push({
								id: check.id,
								batchId: item.batch_id,
								unitId: unitInfo.id,
								houseId: item.house_id,
								problemId: item.id,
								dataState: 0,
								passed: Number(check.status),
								desc: check.description,
								images: '',
								time: check.record_date,
								userId: check.rechecker,
								username: check.recheckName
							})
						})

						//图片
						_.each(item.picture, function(p) {
							tmpImages.push({
								id: p.id,
								batchId: item.batch_id,
								unitId: unitInfo.id,
								problemId: item.id,
								url: p.picture,
								recheckId: p.recheck_record_id,
								status: 0,
								dataState: 0
							})
						})
					});

					//房间-户型关系
					var tmpHouseTypes = [],
						removeHouseTypes = [];
					_.each(data.houseType, function(item, index) {
						if(item.del_flag != '1')
							tmpHouseTypes.push({
								id: item.re_id,
								houseTypeId: item.type_id,
								partId: item.site_id,
								houseTypeName: item.NAME,
								partName: item.siteName,
								renovationType: item.renovation_type || '2'
							});
						if(item.del_flag == '1' && isUpdate) {
							removeHouseTypes.push(item.re_id);
						}
					});

					totalCount += tmpImages.length;
					_.each(tmpImages, function(item) {
						_this.downloadImage(item.url).then(cb).catch(cb);
					})
					if(isUpdate) {
						dao.deleteHouse(removeRooms);
						dao.deleteContractorCheckItemHouseRel(removeContractorRel);
						dao.deleteHouseTypePartRelation(removeHouseTypes);
						dao.deleteProblem(removeProblems);
					}

					dao.addHouse(tmpRooms).then(cb)
					dao.addContractorCheckItemHouseRel(tmpContractorRel).then(cb)
					dao.addProblem(tmpProblems).then(cb);
					dao.addRecheck(tmpRechecks).then(cb);
					dao.addProblemImage(tmpImages).then(cb);
					dao.addHouseTypePartRelation(tmpHouseTypes).then(cb);
				} else
					reject(data);
			})

		},
		downloadImage: function(filename) {
			var url = this.apiServer + 'hfwy/a/jt/checkroomnew/downloadImage';
			return Util.downloadImage(url, filename);
		},
		uploadImage: function(filename) {
			var url = this.apiServer + 'hfwy/check/fileUpLoad';
			return Util.uploadImage(url, '_doc/camera/' + filename);
		},
		/**
		 * 获取最新的APP版本
		 */
		getNewestAppVer: function() {
			var url = this.apiServer + 'hfwy/a/jt/checkroomnew/getApkVesion';
			return this.post(url, {
				platform: plus.os.name == 'iOS' ? 1 : 2
			}).then(function(data) {
				if(data.flag == 1) {
					return Promise.resolve(data.data);
				} else
					return Promise.reject();
			});
		},
		getBatchList: function(userId) { //获取验房列表
			return [{
					id: '1',
					name: '测试任务',
					isDownload: 0,
					isUpdated: 0,
					downloadTime: '',
					buildingName: '测试楼盘1'
				},
				{
					id: '2',
					name: '测试任务2',
					isDownload: 0,
					isUpdated: 0,
					downloadTime: '',
					buildingName: '测试楼盘2'
				},
				{
					id: '3',
					name: '测试任务3',
					isDownload: 0,
					isUpdated: 0,
					downloadTime: '',
					buildingName: '测试楼盘3'
				}
			];
		},
		getUnitList: function() {
			return [{
				id: '1',
				batchId: '1',
				userId: 1,
				name: '1',
				building_name: '20楼',
				developer_name: '万达'

			}, {
				id: '2',
				batchId: '2',
				userId: 1,
				name: '2',
				building_name: '20楼',
				developer_name: '测试开发商'
			}, {
				id: '3',
				batchId: '3',
				userId: 1,
				name: '3',
				building_name: '20楼',
				developer_name: '万达'
			}]
		},
		getHouseList: function(taskId) { //获取房间列表
			return [{
					id: '1',
					batch_id: '1',
					unit_id: '1',
					name: '1101',
					is_updated: false,
					floor: 1, //楼层
					state: 2, //状态 1待检查 2待整改 3已整改 4已通过,
					house_type_id: '1',
					developer_name: '开发商1'
				},
				{
					id: '2',
					batch_id: '1',
					unit_id: '1',
					name: '2101',
					is_updated: false,
					floor: 2, //楼层
					state: 1, //状态 1待检查 2待整改 3已整改 4已通过
					house_type_id: '2',
					developer_name: '开发商2'
				},
				{
					id: '3',
					batch_id: '1',
					unit_id: '1',
					name: '3101',
					is_updated: false,
					floor: 3, //楼层
					state: 1, //状态 1待检查 2待整改 3已整改 4已通过
					house_type_id: '3',
					developer_name: '开发商3'
				},
				{
					id: '4',
					batch_id: '2',
					unit_id: '2',
					name: '4101',
					is_updated: false,
					floor: 4, //楼层
					state: 1, //状态 1待检查 2待整改 3已整改 4已通过
					house_type_id: '1',
					developer_name: '开发商4'
				},
				{
					id: '5',
					batch_id: '3',
					unit_id: '3',
					name: '5101',
					is_updated: false,
					floor: 5, //楼层
					state: 3, //状态 1待检查 2待整改 3已整改 4已通过
					house_type_id: '1',
					developer_name: '开发商5'
				}
			]
		},
		getProblemList: function(houseId) { //获取问题列表
			return [{
					id: '1',
					batch_id: '1', //批次ID
					house_id: '1', //房屋ID
					state: 1, //状态 1待派单 2待整改 3已整改 4已通过
					urgent: false, //是否紧急 false否，true是
					part_name: '客厅1', //检查部位
					desc: '客厅漏水1', //描述
				},
				{
					id: '2',
					batch_id: '1', //批次ID
					house_id: '1', //房屋ID
					state: 2, //状态 1待派单 2待整改 3已整改 4已通过
					urgent: false, //是否紧急 false否，true是
					part_name: '客厅2', //检查部位
					desc: '客厅漏水2', //描述
				},
				{
					id: '3',
					batch_id: '1', //批次ID
					house_id: '1', //房屋ID
					state: 3, //状态 1待派单 2待整改 3已整改 4已通过
					urgent: false, //是否紧急 false否，true是
					part_name: '客厅3', //检查部位
					desc: '客厅漏水3', //描述
				}, {
					id: '4',
					batch_id: '1', //批次ID
					house_id: '1', //房屋ID
					state: 4, //状态 1待派单 2待整改 3已整改 4已通过
					urgent: true, //是否紧急 false否，true是
					part_name: '客厅4', //检查部位
					desc: '客厅漏水4', //描述
				},
				{
					id: '5',
					batch_id: '1', //批次ID
					house_id: '5', //房屋ID
					state: 3, //状态 1待派单 2待整改 3已整改 4已通过
					urgent: true, //是否紧急 false否，true是
					part_name: '客厅4', //检查部位
					desc: '客厅漏水4', //描述
				}
			]
		},
		getProblem: function(problemId) { //获取问题详情
			var list = [null, {
				id: '1',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				number: '0000', //编号
				state: 1, //状态 1待派单 2待整改 3已整改 4已通过
				urgent: false, //是否紧急 false否，true是
				part_name: '客厅', //检查部位
				part_id: '1', //检查部位id
				check_item_name: '地板', //检查项
				check_item_id: '1', //检查项id
				desc: '客厅漏水', //描述,
				desc_id: '1',
				more_desc: '更多描述', //更多描述
				img_before_fix: [], //整改前照片
				img_after_fix: [], //整改后照片
				fix_desc: '我是整改说明', //整改说明
				fix_expire: 1111111111, //整改时限
				duty_id: '1', //责任单位id
				duty_name: '我是责任单位', //责任单位名称
				contractor_id: '1', //承建商id
				contractor_name: '我是承建商', //承建商名称
				fix_live: false, //是否现场整改过
				create_time: '2017-06-22 10:30:55', //登记时间
				fix_time: 1497857074393, //整改时间
			}, {
				id: '2',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				number: '0000', //编号
				state: 2, //状态 1待派单 2待整改 3已整改 4已通过
				urgent: false, //是否紧急 false否，true是
				part_name: '客厅', //检查部位
				part_id: '1', //检查部位id
				check_item_name: '地板', //检查项
				check_item_id: '1', //检查项id
				desc: '客厅漏水', //描述,
				desc_id: '2',
				more_desc: '更多描述', //更多描述
				img_before_fix: [], //整改前照片
				img_after_fix: [], //整改后照片
				fix_desc: '我是整改说明', //整改说明
				fix_expire: 1111111111, //整改时限
				duty_id: '1', //责任单位id
				duty_name: '我是责任单位', //责任单位名称
				contractor_id: '1', //承建商id
				contractor_name: '我是承建商', //承建商名称
				fix_live: false, //是否现场整改过
				create_time: '2017-06-22 10:30:55', //登记时间
				fix_time: 1497857074393, //整改时间
			}, {
				id: '3',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				number: '0000', //编号
				state: 3, //状态 1待派单 2待整改 3已整改 4已通过
				urgent: false, //是否紧急 false否，true是
				part_name: '客厅', //检查部位
				part_id: '1', //检查部位id
				check_item_name: '地板', //检查项
				check_item_id: '1', //检查项id
				desc: '客厅漏水', //描述,
				desc_id: '3',
				more_desc: '更多描述', //更多描述
				img_before_fix: [], //整改前照片
				img_after_fix: [], //整改后照片
				fix_desc: '我是整改说明', //整改说明
				fix_expire: 1111111111, //整改时限
				duty_id: '1', //责任单位id
				duty_name: '我是责任单位', //责任单位名称
				contractor_id: '1', //承建商id
				contractor_name: '我是承建商', //承建商名称
				fix_live: false, //是否现场整改过
				create_time: '2017-06-22 10:30:55', //登记时间
				fix_time: 1497857074393, //整改时间
			}, {
				id: '4',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				number: '0000', //编号
				state: 4, //状态 1待派单 2待整改 3已整改 4已通过
				urgent: false, //是否紧急 false否，true是
				part_name: '客厅', //检查部位
				part_id: '1', //检查部位id
				check_item_name: '地板', //检查项
				check_item_id: '1', //检查项id
				desc: '客厅漏水', //描述,
				desc_id: '1',
				more_desc: '更多描述', //更多描述
				img_before_fix: [], //整改前照片
				img_after_fix: [], //整改后照片
				fix_desc: '我是整改说明', //整改说明
				fix_expire: 1111111111, //整改时限
				duty_id: '1', //责任单位id
				duty_name: '我是责任单位', //责任单位名称
				contractor_id: '1', //承建商id
				contractor_name: '我是承建商', //承建商名称
				fix_live: false, //是否现场整改过
				create_time: '2017-06-22 10:30:55', //登记时间
				fix_time: 1497857074393, //整改时间
			}, {
				id: '5',
				batch_id: '1', //批次ID
				house_id: '5', //房屋ID
				number: '0000', //编号
				state: 3, //状态 1待派单 2待整改 3已整改 4已通过
				urgent: false, //是否紧急 false否，true是
				part_name: '客厅', //检查部位
				part_id: '1', //检查部位id
				check_item_name: '地板', //检查项
				check_item_id: '1', //检查项id
				desc: '客厅漏水', //描述,
				desc_id: '2',
				more_desc: '更多描述', //更多描述
				img_before_fix: [], //整改前照片
				img_after_fix: [], //整改后照片
				fix_desc: '我是整改说明', //整改说明
				fix_expire: 1111111111, //整改时限
				duty_id: '1', //责任单位id
				duty_name: '我是责任单位', //责任单位名称
				contractor_id: '1', //承建商id
				contractor_name: '我是承建商', //承建商名称
				fix_live: false, //是否现场整改过
				create_time: '2017-06-22 10:30:55', //登记时间
				fix_time: 1497857074393, //整改时间
			}];
			if(problemId)
				return list[problemId];
			return list;
		},
		logout: function() {
			localStorage.removeItem('hf_yf_cur_user');
		},
		setCurUser: function(user) {
			localStorage.setItem('hf_yf_cur_user', JSON.stringify(user));
		},
		getCurUser: function() {
			var local = localStorage.getItem('hf_yf_cur_user');
			if(local)
				return JSON.parse(local);
			return local;
		},
		getCurBatch: function() {
			var local = localStorage.getItem('hf_yf_cur_batch');
			if(local)
				return JSON.parse(local);
			return local;
		},
		setCurBatch: function(batch) {
			localStorage.setItem('hf_yf_cur_batch', JSON.stringify(batch));
		},
		getCurUnit: function() {
			var local = localStorage.getItem('hf_yf_cur_unit');
			if(local)
				return JSON.parse(local);
			return local;
		},
		setCurUnit: function(unit) {
			localStorage.setItem('hf_yf_cur_unit', JSON.stringify(unit));
		},
		getCurHouse: function() {
			var local = localStorage.getItem('hf_yf_cur_house');
			if(local)
				return JSON.parse(local);
			return local;
		},
		setCurHouse: function(house) {
			localStorage.setItem('hf_yf_cur_house', JSON.stringify(house));
		},
		setCurProblem: function(problem) {
			localStorage.setItem('hf_yf_cur_problem', JSON.stringify(problem));
		},
		getCurProblem: function() {
			var local = localStorage.getItem('hf_yf_cur_problem');
			if(local)
				return JSON.parse(local);
			return local;
		},
		getReCheckList: function(problemId) { //复验列表
			return [{
				id: '1',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				problem_id: '1', //问题ID
				passed: true, //是否通过
				desc: '我是复验描述', //复验描述
				images: [], //图片列表
				time: 1497852074393, //复验时间
				user_id: '1', //复验用户Id
				username: '测试用户1', //复验用户名
			}, {
				id: '2',
				batch_id: '1', //批次ID
				house_id: '1', //房屋ID
				problem_id: '1', //问题ID
				passed: false, //是否通过
				desc: '我是复验描述2222', //复验描述
				images: [], //图片列表
				time: 1497852074393, //复验时间
				user_id: '1', //复验用户Id
				username: '测试用户1', //复验用户名
			}]
		},
		/**
		 * 部位列表，数据库存的部位表
		 */
		getPartList: function() {
			return [{
				id: '1',
				name: '客厅'
			}, {
				id: '2',
				name: '卧室'
			}, {
				id: '3',
				name: '卫生间'
			}, {
				id: '4',
				name: '阳台'
			}, {
				id: '5',
				name: '办公区'
			}, {
				id: '6',
				name: '商业'
			}]
		},
		/**
		 * 户型列表，数据库的户型表
		 */
		getHouseTypeList: function() {
			return [{
					id: '1',
					name: '一室一厅',
				},
				{
					id: '2',
					name: '办公室'
				}, {
					id: '3',
					name: '商业区'
				}
			]
		},
		/**
		 * 户型和其对应的部位关系表
		 */
		getHouseTypePartRelations: function() {
			return [{
					id: '1',
					house_type_id: '1',
					part_id: '1'
				}, {
					id: '2',
					house_type_id: '1',
					part_id: '2'
				}, {
					id: '3',
					house_type_id: '1',
					part_id: '3'
				},
				{
					id: '4',
					house_type_id: '2',
					part_id: '6'
				}
			]
		},
		/**
		 * 获取检查项列表，
		 */
		getCheckItemList: function() {
			return [{
				id: '1',
				name: '我是检查项1'
			}, {
				id: '2',
				name: '我是检查项2'
			}]
		},
		/**
		 * 获取检查项描述表
		 */
		getCheckItemDescriptionList: function() {
			return [{
				id: '1',
				name: '我是检查项描述1',
				item_id: '1'
			}, {
				id: '2',
				name: '我是检查项描述2',
				item_id: '1'
			}, {
				id: '3',
				name: '我是检查项描述3',
				item_id: '2'
			}]
		},
		/**
		 * 检查项-描述关系表
		 */
		getCheckItemDescriptionRelation: function() {
			return [{
				id: '1',
				item_id: '1',
				desc_id: '1',
			}, {
				id: '2',
				item_id: '2',
				desc_id: '2',
			}, ]
		},
		/**
		 * 获取检查项-部位的关系表
		 */
		getCheckItemPartRelations: function() {
			return [{
				id: '1',
				part_id: '1',
				item_id: '1'
			}, {
				id: '2',
				part_id: '2',
				item_id: '2'
			}]
		},
		/**
		 * 根据房屋id获取有哪些部位
		 * 房屋->户型->户型-部位关系表
		 * @param {Object} houesId
		 */
		getHousePartList: function(houseId) {

		},
		/**
		 * 获取承建商列表
		 */
		getContractorList: function() {
			return [{
				id: '1',
				name: '万达'
			}, {
				id: '2',
				name: '沃尔玛'
			}]
		},
		/**
		 * 获取承建商-检查项-房屋的关系表
		 */
		getContractorCheckItemHouseRel: function() {
			return [{
				id: '1',
				check_item_id: '1',
				contractor_id: '1',
				house_id: '1'
			}, {
				id: '2',
				check_item_id: '2',
				contractor_id: '2',
				house_id: '1'
			}]
		},
		/**
		 * 下载当前用户的任务列表
		 * @param {String} userId
		 */
		downloadBatchs: function(userId, isUpdate) {
			//从服务器下载后，先执行插入操作，再执行update操作
			var batchList = this.getBatchList();
			var unitList = this.getUnitList();
			var count = 0;
			var _this = this;
			return new Promise(function(resolve, reject) {
				if(userId == 1) { //使用本地数据
					_.each(unitList, function(item, index) {
						dao.addUnit({
							id: item.id,
							userId: item.userId,
							batchId: item.batchId,
							name: item.name,
							buildingName: item.building_name,
							developerName: item.developer_name
						})
					})
					batchList.forEach(function(item) {
						item.userId = userId;
						dao.addBatch(item).then(function() {
							count++;
							if(count == batchList.length) {
								dao.updateUserDownload(userId, 1).then(resolve())
							}
						})
					})
				} else { //从服务器取数据
					var url = _this.apiServer + 'hfwy/a/jt/checkroomnew/checkRoomInitData';
					return _this.post(url, {
						userId: userId
					}, isUpdate ? false : true, '初始化数据').then(function(res) {
						if(res.data.length == 0) {
							reject({
								message: '当前用户无验房任务'
							});
							return;
						}
						//先从数据库读取当前有的任务、单元数据
						dao.getBatchList(userId).then(function(localBatchList) {
							var lcBatches = {},
								lcUnits = {};

							_.each(localBatchList, function(batch) {
								lcBatches[batch.id] = batch;
								_.each(batch.units, function(unit) {
									lcUnits[unit.id] = unit;
								})
							})

							if(res.flag == 0) {
								reject(data);
								return;
							}
							var batchList = {};
							var unitList = {};
							var totalCount = 0;
							_.each(res.data, function(item) {
								if(!batchList[item.id] && item.del_flag != '1') {
									batchList[item.id] = {
										id: item.id,
										name: item.batch_name,
										isDownload: 0,
										isUpdated: 0,
										downloadTime: '',
										buildingName: item.building_pro_name,
										userId: userId
									};
									totalCount++;
								}

								var unitKey = item.id + '$$' + item.building_pro_info_id + '$$' + item.building_info_id + '$$' + item.unit;
								if(!unitList[unitKey] && item.del_flag != '1') {
									unitList[unitKey] = {
										id: unitKey,
										batchId: item.id,
										buildingId: item.building_info_id,
										buildingProId: item.building_pro_info_id,
										name: item.unit,
										userId: userId,
										buildingName: item.building_name,
										developerName: item.developer_name,
										downloaded: lcUnits[unitKey] ? lcUnits[unitKey].downloaded : 0,
										downloadTime: lcUnits[unitKey] ? lcUnits[unitKey].download_time : '',
										isUpdated: lcUnits[unitKey] ? lcUnits[unitKey].is_updated : 0
									}
									totalCount++;
								}
							})

							var cb = function() {
								count++;
								if(count == totalCount) {
									dao.updateUserDownload(userId, 1).then(resolve())
								}
							}

							dao.deleteBatchesByUser(userId);

							_.each(unitList, function(item, index) {
								dao.addUnit(item).then(cb);
							})
							_.each(batchList, function(item) {
								item.userId = userId;
								dao.addBatch(item).then(cb)
							})
						}).catch(function(e) {
							reject(e);
						});
					});

				}
			})
		},
		/**
		 * 下载任务内容
		 * @param {Object} unitId
		 */
		downloadBatch: function(unitId) {
			//需添加处理数据库初始化完成的判断
			var houseList = this.getHouseList(),
				problemList = this.getProblem(),
				reCheckList = this.getReCheckList(),
				partList = this.getPartList(),
				houseTypeList = this.getHouseTypeList(),
				houseTypePartRel = this.getHouseTypePartRelations(),
				checkItemList = this.getCheckItemList(),
				partCheckItemRel = this.getCheckItemPartRelations(),
				checkItemDescList = this.getCheckItemDescriptionList(),
				checkItemDescRel = this.getCheckItemDescriptionRelation(),
				contractorList = this.getContractorList(),
				contractorCheckItemHouseRel = this.getContractorCheckItemHouseRel(),
				unitList = this.getUnitList();

			return new Promise(function(resolve, reject) {
				_.each(houseList, function(item, index) {
					dao.addHouse({
						id: item.id,
						batchId: item.batch_id,
						unitId: item.unit_id,
						name: item.name,
						isUpdated: 0,
						floor: item.floor,
						state: item.state,
						houseTypeId: item.house_type_id,
						developerName: item.developer_name
					});
				})

				var tmpProblemList = [];
				_.each(problemList, function(item, index) {
					if(item) {
						tmpProblemList.push({
							id: item.id,
							batchId: item.batch_id,
							houseId: item.house_id,
							dataState: 0,
							state: item.state,
							urgent: item.urgent,
							partId: item.part_id,
							partName: item.part_name,
							desc: item.desc,
							descId: item.desc_id,
							number: item.number,
							checkItemName: item.check_item_name,
							checkItemId: item.check_item_id,
							moreDesc: item.more_desc,
							imgBeforeFix: item.img_before_fix,
							imgAfterFix: item.img_after_fix,
							fixDesc: item.fix_desc,
							fixExpire: item.fix_expire,
							dutyId: item.duty_id,
							dutyName: item.duty_name,
							contractorId: item.contractor_id,
							contractorName: item.contractor_name,
							fixLive: item.fix_live,
							createTime: item.create_time,
							fixTime: item.fix_time
						});
					}

				})
				dao.addProblem(tmpProblemList);

				_.each(reCheckList, function(item, index) {
					dao.addRecheck({
						id: item.id,
						batchId: item.batch_id,
						houseId: item.house_id,
						problemId: item.problem_id,
						dataState: 0,
						passed: item.passed,
						desc: item.desc,
						images: item.images,
						time: item.time,
						userId: item.user_id,
						username: item.username
					});
				})

				//初始化 检查部位、检查项、检查项描述、房屋户型、单位表+++++++++++
				_.each(partList, function(item, index) {
					dao.addPart({
						id: item.id,
						name: item.name
					})
				});

				_.each(houseTypeList, function(item, index) {
					dao.addHouseType({
						id: item.id,
						name: item.name
					})
				})

				_.each(houseTypePartRel, function(item, index) {
					dao.addHouseTypePartRelation({
						id: item.id,
						houseTypeId: item.house_type_id,
						partId: item.part_id
					})
				})

				_.each(checkItemList, function(item, index) {
					dao.addCheckItem({
						id: item.id,
						name: item.name
					})
				})

				_.each(partCheckItemRel, function(item, index) {
					dao.addPartCheckItemRelation({
						id: item.id,
						partId: item.part_id,
						itemId: item.item_id
					})
				})

				_.each(checkItemDescList, function(item, index) {
					dao.addCheckItemDesc({
						id: item.id,
						name: item.name,
						item_id: item.item_id
					})
				})

				//				_.each(checkItemDescRel, function(item, index) {
				//					dao.addCheckItemDescRelation({
				//						id: item.id,
				//						itemId: item.item_id,
				//						descId: item.desc_id
				//					})
				//				})

				_.each(contractorList, function(item, index) {
					dao.addContractor({
						id: item.id,
						name: item.name
					})
				})

				_.each(contractorCheckItemHouseRel, function(item, index) {
					dao.addContractorCheckItemHouseRel({
						id: item.id,
						contractorId: item.contractor_id,
						checkItemId: item.check_item_id,
						houseId: item.house_id
					})
				})

				//初始化 检查部位、检查项、检查项描述、房屋户型、单位表-----------
				setTimeout(function() {
					dao.updateUnitDownLoad({
						id: unitId,
						downloaded: 1
					}).then(function() {
						resolve(true)
					})
				}, 3000);
			})

		},
		/**
		 * 获取当前用户的本地更改、添加的数据
		 */
		getLocalNewAndUpdatedDatasByUser: function(userId) {
			var _this = this;
			return dao.getBatchList(userId).then(function(batchList) {
				var batchIds = batchList.map(function(batch) {
					return batch.id;
				});

				return _this.getLocalNewAndUpdatedDatasByBatch(batchIds)
			})
		},
		/**
		 * 获取单个任务的本地更改、添加的数据
		 */
		getLocalNewAndUpdatedDatasByUnit: function(unitId) {
			var data = {},
				_this = this;
			if(typeof unitId != 'object') //数组
				unitId = [unitId];

			console.log('getLocalNewAndUpdatedDatasByUnit ' + unitId)
			return Promise.all([
				dao.getLocalUpdatedHouses(unitId), dao.getLocalNewAndUpdatedProblems(unitId),
				dao.getLocalNewRechecks(unitId), dao.getLocalNewImages(unitId)
			]).then(function(result) {
				data.houseList = [];
				data.problemList = [];
				data.recheckList = [];
				data.imageList = [];

				var userId = _this.getCurUser().id;
				var optionType = ['', 'update', 'add', 'delete'];

				//房间状态
				_.each(result[0], function(item, index) {
					data.houseList.push({
						id: item.id,
						rectification_status: item.state
					})
				})

				//问题
				_.each(result[1], function(item, index) {
					data.problemList.push({
						id: item.id,
						batchId: item.batch_id,
						houseId: item.house_id,
						partId: item.part_id,
						checkItemId: item.check_item_id,
						content: item.desc_id,
						description: item.more_desc,
						status: item.urgent,
						partContractor: item.contractor_id,
						pass: item.fix_live,
						state: item.state,
						optionType: optionType[item.data_state],
						check_date: item.create_time,
						dutyId: item.duty_id,
						tovoid: '',
						last_check_description: '',
						remarks: '',
						userId: userId
					})
				})

				//复验
				_.each(result[2], function(item, index) {
					data.recheckList.push({
						id: item.id,
						problemsId: item.problem_id,
						rechecker: item.user_id,
						recheckName: item.username,
						description: item.desc,
						status: item.passed ? 1 : 0,
						record_date: item.time,
						userId: userId,
						remarks: '',
					})
				})

				//图片
				_.each(result[3], function(item, index) {
					data.imageList.push({
						id: item.id,
						data_state: item.data_state,
						picture: item.url,
						problemsId: item.problem_id,
						recheckRecordId: item.recheck_id,
						remarks: '',
						userId: userId
					})
				})

				console.log(JSON.stringify(data));
				return Promise.resolve(data);
			})
		},
		/**
		 * 上传单元，根据单元上传
		 * @param {String} unitId
		 */
		uploadUnit: function(unitId, notify) {
			var _this = this;
			var uploadApi = this.apiServer + 'hfwy/a/jt/checkroomnew/uplodaCheckRoomData';

			return new Promise(function(resolve, reject) {
				_this.getLocalNewAndUpdatedDatasByUnit(unitId).then(function(data) {
					var totalCount = data.imageList.length + 1;
					var count = 0;

					var uploadJSON = function() {
						_this.post(uploadApi, { //上传数据
							room: JSON.stringify(data.houseList),
							picture: JSON.stringify(data.imageList),
							problems: JSON.stringify(data.problemList),
							recheckRecord: JSON.stringify(data.recheckList)
						}).then(function(data) {
							//更新相关数据的data_state字段
							console.log('上传成功')
							if(data.flag == 1)
								dao.setDataStateToNormalByUnit(unitId).then(resolve)
							else
								reject(data);
						}).catch(reject)
					};

					//先上传图片，每上传一张后更新数据库
					if(data.imageList.length > 0) {
						_.each(data.imageList, function(item) {
							_this.uploadImage(item.picture).then(function() {
								dao.updateProblemImage({
									id: item.id,
									data_state: Util.dataState.normal
								}).then(function() {
									count++;
									notify && notify(totalCount, count);
									if(count == data.imageList.length) {
										uploadJSON();
									}
								}).catch(reject);
							}).catch(reject);
						})
					} else {
						uploadJSON();
					}
				})
			})
		},
		uploadDemoTest: function() { //接口测试用
			var uploadApi = this.apiServer + 'hfwy/a/jt/checkroomnew/uplodaCheckRoomData';
			var user = this.getCurUser();
			var batch = this.getCurBatch();
			//			this.post(uploadApi,{picture: 'picture',
			//				problems: 'problems',
			//				recheckRecord: 'recheckRecord'});
			//			
			//			return;
			var data = {
				picture: [{
					picture: 'test.jpg',
					problemsId: '1kfdjsalk',
					recheckRecordId: '',
					remarks: '',
					userId: user.id
				}],
				problems: [{
					id: '1kfdjsalk',
					batchId: batch.id,
					houseId: 'lkdfsalkfdsaf',
					partId: 'kdkdkdkd',
					checkItemId: '111',
					content: '1,2',
					description: '无',
					status: 0,
					partContractor: '1',
					pass: 1,
					state: 1,
					optionType: 'add',
					createdDate: Date.now(),
					dutyId: '',
					tovoid: '',
					last_check_description: '',
					remarks: '',
					userId: user.id
				}],
				recheckRecord: [{
					problemsId: '1kfdjsalk',
					rechecker: user.id,
					recheckName: user.username,
					description: '复验测试',
					status: 0,
					record_date: Date.now(),
					userId: user.id,
					remarks: '',
				}]
			};

			this.post(uploadApi, {
				picture: JSON.stringify(data.picture),
				problems: JSON.stringify(data.problems),
				recheckRecord: JSON.stringify(data.recheckRecord)
			}).then(function() {
				console.log('上传成功');
			})
		},

	}

	w.Service = service;
})(window);